import 'dart:async';

import 'package:EZ_Batter/src/tool/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:get/get.dart';

import '../tool/assets.dart';

class AnimationLogo extends StatefulWidget {
  const AnimationLogo({super.key});

  @override
  State<AnimationLogo> createState() => _AnimationLogoState();
}

class _AnimationLogoState extends State<AnimationLogo> {
  final GlobalController modelController = Get.put(GlobalController());
  final GlobalKey<GradientAnimationState> classBKey = GlobalKey<GradientAnimationState>();
  double _progress = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();

    ///模拟充电进度
    // Future.delayed(const Duration(milliseconds: 100), () {
    //   startTimer(context);
    // });
  }

  void setprogressAnimation(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      classBKey.currentState?.setProgress(context, _progress / 100.0);
    });
  }

  void startTimer(BuildContext context) {
    _progress = 0;
    _timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      if (_progress < 1.0) {
        _progress += 0.01;
        classBKey.currentState?.setProgress(context, _progress);
        setState(() {});
      } else {
        _progress = 0;
        // timer.cancel(); // 取消定时器
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constrains) {
      return SizedBox.expand(
        child: Stack(
          children: [
            Positioned.fill(
                child: Center(
              child: UploadAnimation(key: classBKey, height: constrains.maxHeight),
            )),
            Positioned(
                bottom: 0,
                right: 0,
                left: 0,
                child: Obx(() {
                  _progress = modelController.defaultModel.value.rsoc.toDouble();
                  setprogressAnimation(context);
                  return Center(
                      child: Text('${(_progress).toInt()}%',
                          style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold, color: Color_theme)));
                })),
          ],
        ),
      );
    });
  }
}

class UploadAnimation extends GradientAnimation {
  double height;
  UploadAnimation({super.key, required this.height});
  @override
  AlignmentGeometryTween animationAlignmentBetween() {
    return AlignmentGeometryTween(begin: Alignment.bottomCenter, end: Alignment.topCenter);
  }

  @override
  Tween<double> animationBetween() {
    return Tween(begin: 0.0, end: 1.0);
  }

  @override
  List<Color> animationColorBetween() {
    return [Color_theme, Colors.white];
  }

  @override
  Widget animationOnWidget() {
    return Image.asset(
      assets.batter_animation, // 替换为你的图片资源
      height: height,
    );
  }
}
